﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using Lamex.Library;
using Lamex.Interface;
using DevExpress.ClipboardSource.SpreadsheetML;
using DevExpress.Utils.Extensions;

namespace Lamex.mQuality.UI
{
    public partial class frmQC_OQA_Check_Detail : frmBaseChild
    {
        string strSql;
        DataTable dt;
        string strDate_Start, strDate_End, strHNI_Month;
        string strSub_Factory, strCondition;

        public frmQC_OQA_Check_Detail()
        {
            InitializeComponent();
        }

        private void frmQC_OQA_Check_Detail_Load(object sender, EventArgs e)
        {
            try { base.InitButtons(); } catch { }//初始化标准功能，因要应用于RibbonForm，所以加入异常处理

            //dateEdit1只显示年月
            dateEdit1.Properties.CalendarView = DevExpress.XtraEditors.Repository.CalendarView.Vista;
            dateEdit1.Properties.ShowToday = false;
            dateEdit1.Properties.ShowMonthHeaders = true;
            dateEdit1.Properties.VistaCalendarInitialViewStyle = DevExpress.XtraEditors.VistaCalendarInitialViewStyle.YearView;
            dateEdit1.Properties.VistaCalendarViewStyle = DevExpress.XtraEditors.VistaCalendarViewStyle.YearView;
            dateEdit1.Properties.Mask.EditMask = "yyyyMM";
            dateEdit1.Properties.Mask.UseMaskAsDisplayFormat = true;
            dateEdit1.EditValue = DateTime.Now;
            comboBoxEdit1.Text = "全厂";
        }

        private void sbtnView_Click(object sender, EventArgs e)
        {
            /*
             * DECLARE @sql VARCHAR(8000)
SET @sql = 'SELECT [PRODUCT_LINE],[CHECK_DATE],'   
SELECT @sql = @sql + 'SUM(CASE [ISSUE_ITEM] WHEN '''+[ISSUE_ITEM]+''' THEN [ISSUE_QTY] ELSE 0 END) AS '''+QUOTENAME([ISSUE_ITEM])+''','   
FROM (SELECT DISTINCT [ISSUE_ITEM] FROM [QC_OQA_Issue_Record]) AS a     
SELECT @sql = LEFT(@sql,LEN(@sql)-1) + ' FROM [QC_OQA_Issue_Record] GROUP BY [PRODUCT_LINE],[CHECK_DATE]'
PRINT(@sql)
EXEC(@sql)
GO
             */

            //            strSql = @"SELECT *
            //FROM QC_OQA_Issue_Record";

            List<string> lst = new List<string>();
            lst.Add(comboBoxEdit1.Text);
            lst.Add(dateEdit2.Text);
            lst.Add(dateEdit3.Text);

            //exec  p_QC_Issue_RecordList 'Laminate','2020-04-26','2020-05-23'
            dt = Lamex.Base.BaseBuildSql.GetProDataTable("p_QC_Issue_RecordList", lst);
            dt.Columns.RemoveAt(1);
            dt.Columns.RemoveAt(1);

            DataTable temp = dt.Select("", "CHECK_DATE ").CopyToDataTable();
            foreach (DataRow d in temp.Rows)
            {
                d["CHECK_DATE"] = DateTime.Parse(d["CHECK_DATE"].ToString()).ToString("MM-dd");
            }
            DataRow dr = temp.NewRow();
            temp.Rows.Add(dr);
            int iRowCount = temp.Rows.Count;
            decimal iFailSum = 0;
            decimal iCheckTotal = 0;
            
            foreach(DataColumn col in temp.Columns)
            {
                if(!(col.ColumnName== "CHECK_DATE"|| col.ColumnName == "不良率" ))
                {
                    decimal iCount = 0;
                    foreach (DataRow row in temp.Rows)
                    {
                        if(!string.IsNullOrEmpty(row[col.ColumnName].ToString()))
                        {
                            iCount += decimal.Parse (Math.Round(double.Parse( row[col.ColumnName].ToString()),1).ToString());
                            row[col.ColumnName] = decimal.Parse(row[col.ColumnName].ToString())==0?DBNull.Value: (object) Math.Round(double.Parse( row[col.ColumnName].ToString()),1);
                            
                        }
                        else
                        {
                            if (col.ColumnName == "检查数")
                            {
                                if (string.IsNullOrEmpty(row[col.ColumnName].ToString()))
                                    row["不良率"] = "无检查数";
                            }
                        }
                        
                    }
                    temp.Rows[iRowCount - 1][col.ColumnName] = iCount;

                    if (col.ColumnName == "合计")
                        iFailSum = iCount;
                    if (col.ColumnName == "检查数")
                        iCheckTotal = iCount;

                }
                
            }
            
            if(temp.Rows.Count!=0)
            {
                temp.Rows[iRowCount - 1]["CHECK_DATE"] = "小计";
                if (iCheckTotal!=0)
                    temp.Rows[iRowCount - 1]["不良率"] = Math.Round(double.Parse((iFailSum / iCheckTotal * 100).ToString()), 2) + "%"; 
            }

            DataRow drow = temp.NewRow();
            drow.ItemArray = temp.Rows[iRowCount - 1].ItemArray;
            temp.Rows.InsertAt(drow,0);
            temp.Rows.RemoveAt(temp.Rows.Count - 1);
            temp.Columns[0].ColumnName = "检查日期";
            vGridControl1.Rows.Clear();

            
            vGridControl1.DataSource = temp;
            //for (int i = 0; i < vGridControl1.Rows.Count; i++)
            //{
            //    vGridControl1.Rows[i]
            //}

            vGridControl1.OptionsView.AutoScaleBands = true;

            RecalcWidth(temp);
            //vGridControl1列宽自适应
            //TO DO
        }
        private void RecalcWidth(DataTable dt)
        {
            int recordWidth = (vGridControl1.Width - vGridControl1.RowHeaderWidth) / dt.Rows.Count;
            if (recordWidth > vGridControl1.RecordMinWidth)
            {
                vGridControl1.RecordWidth = 55;
                vGridControl1.ScrollVisibility = DevExpress.XtraVerticalGrid.ScrollVisibility.Vertical;
            }
            else
            {
                vGridControl1.ScrollVisibility = DevExpress.XtraVerticalGrid.ScrollVisibility.Auto;
            }
            vGridControl1.RowHeaderWidth= 150;
        }
        private void dateEdit1_EditValueChanged(object sender, EventArgs e)
        {
            #region 初始化界面图表

            vGridControl1.OptionsBehavior.Editable = false;
            vGridControl1.DataSource = null;

            dateEdit2.EditValue = null;
            dateEdit3.EditValue = null;
            strDate_Start = "";
            strDate_End = "";

            #endregion

            //首先判断数据库是否有dateEdit1.Text，再取TOP 2
            if (string.IsNullOrEmpty(dateEdit1.Text))
            {
                return;
            }

            DataTable dt1 = Lamex.Base.BaseBuildSql.GetDataTableBySql("select top 2 * from Cost_HNI_Calendar where YEAR_MONTH='" + dateEdit1.Text + "'  order by YEAR_MONTH");////AAA

            if (dt1.Rows.Count == 0)
            {
                return;
            }
            DataTable dt = Lamex.Base.BaseBuildSql.GetDataTableBySql("select top 2 * from Cost_HNI_Calendar where YEAR_MONTH>='" + dateEdit1.Text + "'  order by YEAR_MONTH");
            if (dt.Rows.Count == 2)
            {
                strDate_Start = dt.Rows[0]["FIRST_DATE"].ToString();
                strDate_End = Convert.ToDateTime(dt.Rows[1]["FIRST_DATE"].ToString()).AddDays(-1).ToString("yyyy-MM-dd");
                dateEdit2.DateTime = Convert.ToDateTime(strDate_Start);
                dateEdit3.DateTime = Convert.ToDateTime(strDate_End); ;
            }
            else
            {
                XtraMessageBox.Show("无法获取起始日或结束日，HNI日历未维护所选月份数据！");
                return;
            }
        }

        public override void DoView(IButtonInfo sender)
        {
            sbtnView_Click(null, null);
            base.DoView(sender);
        }

        public override void DoExport(IButtonInfo sender)
        {
            //TO DO
            //Lamex.Common.ExecelHelper.GridViewToExcel(vGridControl1);
            base.DoExport(sender);
        }

    }
}
 